package com.canbot.u05.api;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.control.RobotMgr;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.update.ConstUtils;
import com.canbot.u05.update.RobotUtil;
import com.canbot.u05.utils.Logger;
import com.coolerfall.download.DownloadCallback;
import com.coolerfall.download.DownloadManager;
import com.coolerfall.download.DownloadRequest;
import com.coolerfall.download.OkHttpDownloader;
import com.coolerfall.download.Priority;

import java.io.File;
import java.util.concurrent.TimeUnit;


/**
 * 处理胸口发送过来的消息数据
 */

public class ReceiveData {

        private static final String TAG = "ReceiveData";

        private Context mContext;

        private MyReceiveDataInterface listener;

        /**
         * 处理胸口发送过来的消息
         */
        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        String msgData = (String) msg.obj;
                        Logger.e(TAG, "msg.what " + msg.what + " msg.obj: " + msg.obj);
                        switch (msg.what) {
                                // 胸口平板通知更新
                                case MsgType.MOBILE_PAD_VERSION_UPDAT:
                                        if (msgData.isEmpty() || !msgData.endsWith("apk")) {
                                                return;
                                        }
                                        else {
                                                downloadApk(msgData);
                                        }
                                        break;
//                                //接受导览任务相关的结果
//                                case MsgType.MOBILE_PAD_MAP_TASK:
//                                        EventBus.getDefault().post(new StringMsgBean(MsgType.MOBILE_PAD_MAP_TASK, msgData));
//                                        break;
//                                //收到胸口返回的心跳消息
//                                case  9004:
//                                        Intent intent = new Intent();
//                                        intent.setAction(com.canbot.u05.utils.ConstUtils.ACTION_DISCONNECT_SUCCESS);
//                                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
//                                        break;

                        }
                }
        };

        /**
         * 根据胸口传来的路径去下载 apk
         *
         * @param url apk 下载路径
         */
        private void downloadApk(String url) {
                if (url.isEmpty() || !url.endsWith(".apk")) {
                        return;
                }
                File file = new File(ConstUtils.PATH_UPDATE_APK);
                if (!file.exists()) {
                        file.mkdirs();
                }
                String name = url.substring(url.lastIndexOf("/") + 1);
                String destPath = ConstUtils.PATH_UPDATE_APK + name;
                final String downloadUrl = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + url;
                DownloadRequest request = new DownloadRequest.Builder().url(downloadUrl).retryTime(1).retryInterval(1, TimeUnit.SECONDS).progressInterval(1, TimeUnit
                        .SECONDS).priority(Priority.HIGH).allowedNetworkTypes(DownloadRequest.NETWORK_WIFI).destinationFilePath(destPath).downloadCallback
                        (new DownloadCallback() {
                                @Override
                                public void onStart(int downloadId, long totalBytes) {
                                        Logger.e(TAG, "start download " + downloadUrl);
                                }

                                @Override
                                public void onRetry(int downloadId) {
                                }

                                @Override
                                public void onProgress(int downloadId, long bytesWritten, long totalBytes) {
                                        //                showProgress((int) (bytesWritten * 100 / totalBytes));
                                }

                                @Override
                                public void onSuccess(int downloadId, String filePath) {
                                        Logger.e(TAG, "download succeed " + filePath);
                                        RobotUtil.install(new File(filePath), MainApplication.getInstance());
                                }

                                @Override
                                public void onFailure(int downloadId, int statusCode, String errMsg) {
                                        Logger.e(TAG, "downloadApk failed " + errMsg);
                                }
                        }).build();
                new DownloadManager.Builder().context(MainApplication.getInstance()).downloader(OkHttpDownloader.create()).threadPoolSize(2).build().add(request);
        }

        public ReceiveData(Context context) {
                this.mContext = context;
                listener = new MyReceiveDataInterface();
                RobotMgr.getInstance().init(listener);
        }

        /**
         * 接收处理胸口发来的消息
         */
        public class MyReceiveDataInterface implements ReceiveDataInterface {

                @Override
                public void onReceive(String data) {
                        Logger.e(TAG, "ReceiveData data===" + data);

//            Looper.prepare();
//            Toast.makeText(mContext,data, Toast.LENGTH_SHORT).show();
//            Looper.loop();

                        if (data != null) {
                                StringMsgBean strMsgBean = JSON.parseObject(data, StringMsgBean.class);
                                if (strMsgBean != null) {
                                        int msgType = strMsgBean.getMsgType();
                                        String msgData = strMsgBean.getMsgData();
                                        Logger.e(TAG, "ReceiveData StringMsgBean===" + strMsgBean.toString() + ",msgType=  " + msgType);
                                        mHandler.obtainMessage(msgType, msgData).sendToTarget();
                                }
                        }
                }
        }
}
